package cn.cloudreal.cbms.castDetail.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.log4j.Logger;
import org.apache.poi.hwpf.usermodel.BorderCode;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import cn.cloudreal.cbms.Dictionary.service.DictionaryService;
import cn.cloudreal.cbms.castDetail.service.CastDetailService;
import cn.cloudreal.cbms.common.util.Arith;
import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.DatadicContext;
import cn.cloudreal.cbms.common.util.PageBean;
import cn.cloudreal.cbms.common.util.StringUtils;
import cn.cloudreal.cbms.vo.Dictionary;
import cn.cloudreal.cbms.vo.Material;
import cn.cloudreal.cbms.vo.QueryArrangement;
import cn.cloudreal.cbms.vo.UserInfo;

import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * Title: CBM
 * </p>
 * <p>
 * Description:项目排期表服务层视图类
 * </p>
 * <p>
 * Copyright: Copyright (c) 2012
 * </p>
 * <p>
 * Company:云恒瑞通
 * </p>
 * 
 * @author WangTao
 * @date 2012-08-14
 */
public class ArrangementAction extends ActionSupport
{

    /** serialVersionUID */
    private static final long serialVersionUID = 1L;

    /** 日志工具类实例 */
    private static final Logger log = Logger.getLogger(ArrangementAction.class);

    /** 服务 */
    CastDetailService castDetailService;

    DictionaryService dictionaryService;

    /** 当前页 */
    int currentPage;

    /** 分页对象 */
    PageBean page;

    /** 媒体资源类型 */
    List<Dictionary> mediaTypeSelect = new ArrayList<Dictionary>();

    /** 地市下拉 */
    List<Dictionary> citySelect = new ArrayList<Dictionary>();

    /** 排期开始时间 */
    String arrangementStartTime;

    /** 排期结束时间 */
    String arrangementEndTime;

    /** 媒体类型 */
    String mediaType;

    /** 年度 */
    String year;

    List<QueryArrangement> arrangements = new ArrayList<QueryArrangement>();

    QueryArrangement totalArrangement = new QueryArrangement();

    /** 表头 */
    List<String> tableField = new ArrayList<String>();

    int totalDays;

    int startDay;

    int endDay;

    int totalFields;

    boolean exportAll = false;

    /** 表值 */
    List<String> tableFieldValue = new ArrayList<String>();

    /** 地市 */
    String city;

    /**
     * 排期查询初始化
     * 
     * @return String
     */
    public String initQueryArrangement()
    {
        // 返回值
        String resultName = null;
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter CastDetailAction initQueryArrangement() method, return String");
        }
        try
        {
            // 初始化分页对象
            page = new PageBean(currentPage == 0 ? 1 : currentPage,
                    Constants.PAGE_SIZE);
            // 查询媒体类型
            Dictionary dic = new Dictionary();
            dic.setParentId(-1);
            dic.setClasscode("MTLX");
            dic.setExtAttr3("1");
            mediaTypeSelect = dictionaryService.findAll(dic);// 媒介属性LIst
            // 获取当前session对象中所属城市
            UserInfo userInfo = (UserInfo) ServletActionContext.getRequest()
                    .getSession()
                    .getAttribute(Constants.SESSIONPRKEY);
            // 非空
            if (null != userInfo)
            {
                //
                if (userInfo.getUserRole() != null)
                {
                    // 默认东莞
                    String userCity = "DG";
                    // 非空重置
                    if (userInfo.getUsercity() != null)
                    {
                        if (!"".equals(userInfo.getUsercity()))
                        {
                            userCity = userInfo.getUsercity();
                        }
                    }
                    // 地市
                    if (city == null || "".equals(city))
                    {
                        city = userCity;
                    }
                    // 操作范围
                    String roleRange = userInfo.getUserRole().getRoleRange();
                    //
                    if (roleRange != null)
                    {
                        // 省
                        if ("1".endsWith(roleRange))
                        {
                            //
                            citySelect = DatadicContext.getInstance()
                                    .getDicDataListByCode("CITY");
                            // 初始化年度
                            year = (new Date().getYear() + 1900) + "";
                            // 重置返回值
                            resultName = SUCCESS;
                        }
                        // 地市级
                        else if ("2".endsWith(roleRange))
                        {
                            //
                            Dictionary cityDictionary = DatadicContext.getInstance()
                                    .getDatadicObject(city, "CITY");
                            if (cityDictionary != null)
                            {
                                citySelect.add(cityDictionary);
                            }
                            // 初始化年度
                            year = (new Date().getYear() + 1900) + "";
                            // 重置返回值
                            resultName = SUCCESS;
                        }
                        // 个人
                        else if ("3".endsWith(roleRange))
                        {
                            //
                            Dictionary cityDictionary = DatadicContext.getInstance()
                                    .getDatadicObject(city, "CITY");
                            if (cityDictionary != null)
                            {
                                citySelect.add(cityDictionary);
                            }
                            // 初始化年度
                            year = (new Date().getYear() + 1900) + "";
                            // 重置返回值
                            resultName = SUCCESS;
                        }
                    }

                }
            }
        }
        catch (Exception e)
        {
            // 打印异常信息
            e.printStackTrace();
            // 打印异常方法体日志
            if (log.isInfoEnabled())
            {
                log.error("Exception CastDetailAction initQueryArrangement() method, return String",
                        e);
            }
            // 重置返回值
            resultName = ERROR;
        }
        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit CastDetailAction initQueryArrangement() method, return String");
        }
        return resultName;
    }

    /**
     * 排期查询
     * 
     * @return String
     */
    public String queryArrangement()
    {
        // 返回值
        String resultName = null;
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter CastDetailAction queryArrangement() method, return String");
        }
        try
        {

            // 类型非空
            if (!"".equals(mediaType))
            {
                // 初始化
                initQueryArrangement();
                // 获取当前session对象中所属城市
                UserInfo userInfo = (UserInfo) ServletActionContext.getRequest()
                        .getSession()
                        .getAttribute(Constants.SESSIONPRKEY);
                // 查询条件封装
                Map condition = new HashMap();
                condition.put("year", year);
                condition.put("mediaType", mediaType);
                condition.put("arrangementStartTime", arrangementStartTime);
                condition.put("arrangementEndTime", arrangementEndTime);
                condition.put("startDay",
                        StringUtils.getDayByDate(arrangementStartTime));
                condition.put("endDay",
                        StringUtils.getDayByDate(arrangementEndTime));
                if (exportAll)
                {
                    condition.put("exportAll", "exportAll");
                    exportAll = false;
                }
                // 判断所选择的字段
                arrangementStartTime = arrangementStartTime == null ? ""
                        : arrangementStartTime;
                arrangementEndTime = arrangementEndTime == null ? ""
                        : arrangementEndTime;

                totalDays = StringUtils.getNumberOfDays(arrangementStartTime,
                        arrangementEndTime) + 1;
                if (arrangementStartTime.equals(""))
                {
                    startDay = 0;
                }
                else
                {
                    startDay = Integer.valueOf(arrangementStartTime.substring(8));
                }
                if (arrangementEndTime.equals(""))
                {
                    endDay = 0;
                }
                else
                {
                    endDay = Integer.valueOf(arrangementEndTime.substring(8));
                }
                // totalArrangement.setMediumArrangementArray(new
                // String[totalDays]);
                String[] totalMediumArrangementArray = new String[totalDays];
                //
                totalFields = totalDays * 30;
                //
                Dictionary dic = new Dictionary();
                dic.setParentId(Integer.valueOf(mediaType));
                dic.setClasscode("MJZDPZ");
                dic.setOrderBy("extAttr4");// 用于排序
                dic.setExtAttr3("1");
                List<Dictionary> subDatadics = dictionaryService.findAll(dic);// 媒介属性LIst
                //
                StringBuffer dbField = new StringBuffer();
                // 遍历
                for (Dictionary subDatadic : subDatadics)
                {
                    //
                    tableField.add(subDatadic.getDatavalue());
                    //
                    // tableFieldValue.add(subDatadic.getId());
                    //
                    dbField.append(",d." + subDatadic.getId());
                    //
                    totalFields += 150;
                }
                // 非空
                if (null != userInfo)
                {
                    //
                    if (userInfo.getUserRole() != null)
                    {
                        // 操作范围
                        String roleRange = userInfo.getUserRole()
                                .getRoleRange();
                        //
                        if (roleRange != null)
                        {
                            // 省
                            if ("1".endsWith(roleRange))
                            {
                                // 地市
                                condition.put("city", city);
                                //
                                page.setTotalRecords(castDetailService.queryArrangementCount(condition));
                                //
                                arrangements = castDetailService.queryArrangement(condition,
                                        page);
                                // 遍历
                                for (QueryArrangement arrangement : arrangements)
                                {
                                    // 计算折后刊例
                                    arrangement.setMediumDisPrice(Arith.div(Arith.mul(arrangement.getMediumPrice(),
                                            arrangement.getMediumOrientDiscount()),
                                            100));
                                    //
                                    arrangement.setMediumStatus(DatadicContext.getInstance()
                                            .getDatadicObject(arrangement.getMediumStatus(),
                                                    "MJSYQK")
                                            .getDatavalue());
                                    //
                                    if (Integer.valueOf(arrangementStartTime.replaceAll("-",
                                            "")) >= Integer.valueOf(arrangement.getFactStartTime()
                                            .replaceAll("-", "")))
                                    {
                                        arrangement.setFactStartTime(arrangementStartTime);
                                    }
                                    if (Integer.valueOf(arrangementEndTime.replaceAll("-",
                                            "")) <= Integer.valueOf(arrangement.getFactEndTime()
                                            .replaceAll("-", "")))
                                    {
                                        arrangement.setFactEndTime(arrangementEndTime);
                                    }
                                    String[] mediumArrangementArray = StringUtils.getSubArrangement(arrangementStartTime,
                                            arrangementEndTime,
                                            arrangement.getMediumArrangement(),
                                            totalDays,
                                            arrangement);
                                    // 查询不同媒体类型下的媒介字段
                                    // 非空
                                    if (dbField.length() != 0)
                                    {
                                        condition.put("dbField",
                                                dbField.toString().substring(1));
                                    }
                                    condition.put("id_medium",
                                            arrangement.getId_medium());
                                    arrangement.setTableFieldValue(castDetailService.getMediumByField(condition));
                                    //
                                    for (int i = 0; i < mediumArrangementArray.length; i++)
                                    {
                                        if (!"--".equals(mediumArrangementArray[i]))
                                        {
                                            if (!"--".equals(totalMediumArrangementArray[i]))
                                            {
                                                // 累加次数
                                                arrangement.setMediumAmount(arrangement.getMediumAmount()
                                                        + Integer.valueOf(mediumArrangementArray[i]));
                                                // 累加每日次数
                                                if (totalMediumArrangementArray[i] != null)
                                                {
                                                    totalMediumArrangementArray[i] = (Integer.valueOf(totalMediumArrangementArray[i]) + Integer.valueOf(mediumArrangementArray[i]))
                                                            + "";
                                                }
                                                else
                                                {
                                                    totalMediumArrangementArray[i] = mediumArrangementArray[i];
                                                }
                                            }
                                            else
                                            {
                                                // 累加次数
                                                arrangement.setMediumAmount(arrangement.getMediumAmount()
                                                        + Integer.valueOf(mediumArrangementArray[i]));
                                                // 累加每日次数
                                                if (totalMediumArrangementArray[i] != null)
                                                {
                                                    totalMediumArrangementArray[i] = mediumArrangementArray[i];
                                                }
                                                else
                                                {
                                                    totalMediumArrangementArray[i] = arrangement.getMediumAmount()
                                                            + "";
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if ("--".equals(totalMediumArrangementArray[i]))
                                            {
                                                totalMediumArrangementArray[i] = "--";
                                            }
                                        }
                                    }
                                    //
                                    arrangement.setMediumArrangementArray(mediumArrangementArray);
                                    //
                                    totalArrangement.setMediumAmount(totalArrangement.getMediumAmount()
                                            + arrangement.getMediumAmount());
                                    //
                                    totalArrangement.setMediumArrangementArray(totalMediumArrangementArray);
                                }
                            }
                            // 地市级
                            else if ("2".endsWith(roleRange))
                            {
                                // 地市
                                condition.put("city", userInfo.getUsercity());
                                //
                                page.setTotalRecords(castDetailService.queryArrangementCount(condition));
                                //
                                arrangements = castDetailService.queryArrangement(condition,
                                        page);
                                // 遍历
                                for (QueryArrangement arrangement : arrangements)
                                {
                                    // 计算折后刊例

                                    // 计算折后刊例
                                    arrangement.setMediumDisPrice(Arith.div(Arith.mul(arrangement.getMediumPrice(),
                                            arrangement.getMediumOrientDiscount()),
                                            100));
                                    //
                                    arrangement.setMediumStatus(DatadicContext.getInstance()
                                            .getDatadicObject(arrangement.getMediumStatus(),
                                                    "MJSYQK")
                                            .getDatavalue());
                                    //
                                    if (Integer.valueOf(arrangementStartTime.replaceAll("-",
                                            "")) >= Integer.valueOf(arrangement.getFactStartTime()
                                            .replaceAll("-", "")))
                                    {
                                        arrangement.setFactStartTime(arrangementStartTime);
                                    }
                                    if (Integer.valueOf(arrangementEndTime.replaceAll("-",
                                            "")) <= Integer.valueOf(arrangement.getFactEndTime()
                                            .replaceAll("-", "")))
                                    {
                                        arrangement.setFactEndTime(arrangementEndTime);
                                    }
                                    String[] mediumArrangementArray = StringUtils.getSubArrangement(arrangementStartTime,
                                            arrangementEndTime,
                                            arrangement.getMediumArrangement(),
                                            totalDays,
                                            arrangement);
                                    // 查询不同媒体类型下的媒介字段
                                    // 非空
                                    if (dbField.length() != 0)
                                    {
                                        condition.put("dbField",
                                                dbField.toString().substring(1));
                                    }
                                    condition.put("id_medium",
                                            arrangement.getId_medium());
                                    arrangement.setTableFieldValue(castDetailService.getMediumByField(condition));
                                    //
                                    for (int i = 0; i < mediumArrangementArray.length; i++)
                                    {
                                        if (!"--".equals(mediumArrangementArray[i]))
                                        {
                                            if (!"--".equals(totalMediumArrangementArray[i]))
                                            {
                                                // 累加次数
                                                arrangement.setMediumAmount(arrangement.getMediumAmount()
                                                        + Integer.valueOf(mediumArrangementArray[i]));
                                                // 累加每日次数
                                                if (totalMediumArrangementArray[i] != null)
                                                {
                                                    totalMediumArrangementArray[i] = (Integer.valueOf(totalMediumArrangementArray[i]) + Integer.valueOf(mediumArrangementArray[i]))
                                                            + "";
                                                }
                                                else
                                                {
                                                    totalMediumArrangementArray[i] = mediumArrangementArray[i];
                                                }
                                            }
                                            else
                                            {
                                                // 累加次数
                                                arrangement.setMediumAmount(arrangement.getMediumAmount()
                                                        + Integer.valueOf(mediumArrangementArray[i]));
                                                // 累加每日次数
                                                if (totalMediumArrangementArray[i] != null)
                                                {
                                                    totalMediumArrangementArray[i] = mediumArrangementArray[i];
                                                }
                                                else
                                                {
                                                    totalMediumArrangementArray[i] = arrangement.getMediumAmount()
                                                            + "";
                                                }
                                            }
                                        }
                                        else
                                        {
                                            totalMediumArrangementArray[i] = "--";
                                        }
                                    }
                                    //
                                    arrangement.setMediumArrangementArray(mediumArrangementArray);
                                    //
                                    totalArrangement.setMediumAmount(totalArrangement.getMediumAmount()
                                            + arrangement.getMediumAmount());
                                    //
                                    totalArrangement.setMediumArrangementArray(totalMediumArrangementArray);
                                }
                            }
                            // 个人
                            else if ("3".endsWith(roleRange))
                            {
                                // 用户
                                condition.put("creator", userInfo.getUserCode());
                                //
                                page.setTotalRecords(castDetailService.queryArrangementCount(condition));
                                //
                                arrangements = castDetailService.queryArrangement(condition,
                                        page);
                                // 遍历
                                for (QueryArrangement arrangement : arrangements)
                                {
                                    // 计算折后刊例

                                    // 计算折后刊例
                                    arrangement.setMediumDisPrice(Arith.div(Arith.mul(arrangement.getMediumPrice(),
                                            arrangement.getMediumOrientDiscount()),
                                            100));
                                    //
                                    arrangement.setMediumStatus(DatadicContext.getInstance()
                                            .getDatadicObject(arrangement.getMediumStatus(),
                                                    "MJSYQK")
                                            .getDatavalue());
                                    //
                                    if (Integer.valueOf(arrangementStartTime.replaceAll("-",
                                            "")) >= Integer.valueOf(arrangement.getFactStartTime()
                                            .replaceAll("-", "")))
                                    {
                                        arrangement.setFactStartTime(arrangementStartTime);
                                    }
                                    if (Integer.valueOf(arrangementEndTime.replaceAll("-",
                                            "")) <= Integer.valueOf(arrangement.getFactEndTime()
                                            .replaceAll("-", "")))
                                    {
                                        arrangement.setFactEndTime(arrangementEndTime);
                                    }
                                    String[] mediumArrangementArray = StringUtils.getSubArrangement(arrangementStartTime,
                                            arrangementEndTime,
                                            arrangement.getMediumArrangement(),
                                            totalDays,
                                            arrangement);
                                    // 查询不同媒体类型下的媒介字段
                                    // 非空
                                    if (dbField.length() != 0)
                                    {
                                        condition.put("dbField",
                                                dbField.toString().substring(1));
                                    }
                                    condition.put("id_medium",
                                            arrangement.getId_medium());
                                    arrangement.setTableFieldValue(castDetailService.getMediumByField(condition));
                                    //
                                    for (int i = 0; i < mediumArrangementArray.length; i++)
                                    {
                                        if (!"--".equals(mediumArrangementArray[i]))
                                        {
                                            if (!"--".equals(totalMediumArrangementArray[i]))
                                            {
                                                // 累加次数
                                                arrangement.setMediumAmount(arrangement.getMediumAmount()
                                                        + Integer.valueOf(mediumArrangementArray[i]));
                                                // 累加每日次数
                                                if (totalMediumArrangementArray[i] != null)
                                                {
                                                    totalMediumArrangementArray[i] = (Integer.valueOf(totalMediumArrangementArray[i]) + Integer.valueOf(mediumArrangementArray[i]))
                                                            + "";
                                                }
                                                else
                                                {
                                                    totalMediumArrangementArray[i] = mediumArrangementArray[i];
                                                }
                                            }
                                            else
                                            {
                                                // 累加次数
                                                arrangement.setMediumAmount(arrangement.getMediumAmount()
                                                        + Integer.valueOf(mediumArrangementArray[i]));
                                                // 累加每日次数
                                                if (totalMediumArrangementArray[i] != null)
                                                {
                                                    totalMediumArrangementArray[i] = mediumArrangementArray[i];
                                                }
                                                else
                                                {
                                                    totalMediumArrangementArray[i] = arrangement.getMediumAmount()
                                                            + "";
                                                }
                                            }
                                        }
                                        else
                                        {
                                            totalMediumArrangementArray[i] = "--";
                                        }
                                    }
                                    //
                                    arrangement.setMediumArrangementArray(mediumArrangementArray);
                                    //
                                    totalArrangement.setMediumAmount(totalArrangement.getMediumAmount()
                                            + arrangement.getMediumAmount());
                                    //
                                    totalArrangement.setMediumArrangementArray(totalMediumArrangementArray);
                                }
                            }
                        }
                    }
                }
            }
            // 媒体类型
            String mediaTypeDatavalue = DatadicContext.getInstance()
                    .getDatadicObject(mediaType, "MTLX")
                    .getDatavalue();
            // 判断属于哪个类型
            if (mediaTypeDatavalue.indexOf("户外") != -1)
            {
                //
                totalFields = totalFields - totalDays * 30;
                // 重置返回值
                resultName = SUCCESS + "1";
            }
            else if (mediaTypeDatavalue.indexOf("网络") != -1)
            {
                //
                totalFields = totalFields - totalDays * 30;
                // 重置返回值
                resultName = SUCCESS + "1";
            }
            else
            {
                // 重置返回值
                resultName = SUCCESS;
            }
        }
        catch (Exception e)
        {
            // 打印异常信息
//            e.printStackTrace();
            // 打印异常方法体日志
            if (log.isInfoEnabled())
            {
                log.error("Exception CastDetailAction queryArrangement() method, return String",
                        e);
            }
            // 重置返回值
            resultName = ERROR;
        }
        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit CastDetailAction queryArrangement() method, return String");
        }
        return resultName;
    }

    // /**
    // * 排期查询
    // *
    // * @return String
    // */
    // public String queryArrangement()
    // {
    // // 返回值
    // String resultName = null;
    // // 打印进入方法体日志
    // if (log.isInfoEnabled())
    // {
    // log.info("Enter CastDetailAction queryArrangement() method, return String");
    // }
    // try
    // {
    // // 判断所选择的字段
    // arrangementStartTime = arrangementStartTime == null ? ""
    // : arrangementStartTime;
    // arrangementEndTime = arrangementEndTime == null ? ""
    // : arrangementEndTime;
    // // 各种非空
    // if (!"".equals(mediaType)
    // && (!"".equals(arrangementStartTime) &&
    // (!"".equals(arrangementEndTime))))
    // {
    // // 初始化
    // initQueryArrangement();
    // // 获取当前session对象中所属城市
    // UserInfo userInfo = (UserInfo) ServletActionContext.getRequest()
    // .getSession()
    // .getAttribute(Constants.SESSIONPRKEY);
    // // 查询条件封装
    // Map condition = new HashMap();
    // condition.put("year", year);
    // condition.put("mediaType", mediaType);
    // condition.put("arrangementStartTime", arrangementStartTime);
    // condition.put("arrangementEndTime", arrangementEndTime);
    // // 导出标志
    // if (exportAll)
    // {
    // condition.put("exportAll", "exportAll");
    // exportAll = false;
    // }
    // // 获取相关字段
    // Dictionary dic = new Dictionary();
    // dic.setParentid(mediaType);
    // dic.setClasscode("MJZDPZ");
    // dic.setOrderBy("extAttr4");// 用于排序
    // dic.setExtAttr3("1");
    // List<Dictionary> subDatadics = dictionaryService.findAll(dic);// 媒介属性LIst
    // // 媒体类型
    // String mediaTypeDatavalue = DatadicContext.getInstance()
    // .getDatadicObject(mediaType, "MTLX")
    // .getDatavalue();
    // // 判断属于哪个类型
    // if (mediaTypeDatavalue.indexOf("报纸") != -1)
    // {
    // // 报纸
    //                    
    // }
    // else if (mediaTypeDatavalue.indexOf("杂志") != -1)
    // {
    // // 杂志
    // }
    // else if (mediaTypeDatavalue.indexOf("网络") != -1)
    // {
    // // 网络
    // }
    // else if (mediaTypeDatavalue.indexOf("户外") != -1)
    // {
    // // 户外
    // }
    // else if (mediaTypeDatavalue.indexOf("电台") != -1)
    // {
    // // 电台
    // }
    // else if (mediaTypeDatavalue.indexOf("电视") != -1)
    // {
    // // 电视
    // }
    //
    // // 开始
    // startDay = Integer.valueOf(arrangementStartTime.substring(8));
    // // 结束
    // endDay = Integer.valueOf(arrangementEndTime.substring(8));
    // //
    // }
    // // 重置返回值
    // resultName = SUCCESS;
    // }
    // catch (Exception e)
    // {
    // // 打印异常信息
    // e.printStackTrace();
    // // 打印异常方法体日志
    // if (log.isInfoEnabled())
    // {
    // log.error("Exception CastDetailAction queryArrangement() method, return String",
    // e);
    // }
    // // 重置返回值
    // resultName = ERROR;
    // }
    // // 打印退出方法体日志
    // if (log.isInfoEnabled())
    // {
    // log.info("Exit CastDetailAction queryArrangement() method, return String");
    // }
    // return resultName;
    // }

    /**
     * 排期查询导出
     * 
     * @return String
     */
    public String exportExcel()
    {
        try
        {
        // 返回值
        String resultName = null;
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter CastDetailAction exportExcel() method, return String");
        }
        
            if (!"".equals(mediaType))
            {
                //
                exportAll = true;
                //
                boolean bool = true;
                // 返回
                resultName = queryArrangement();
                //
                if (resultName.indexOf(SUCCESS) != -1)
                {

                    boolean exportFlag = false;
                    //
                    String templateFileType = DatadicContext.getInstance()
                            .getDatadicObject(mediaType, "MTLX")
                            .getExtAttr2();
                    //
                    HttpServletResponse response = ServletActionContext.getResponse();
                    String fileName = arrangementStartTime.substring(0, 7)
                            .replace("-", "年")
                            + "月"
                            + templateFileType
                            + "排期"
                            + new SimpleDateFormat("MMdd").format(new Date())
                            + ".xlsx";
                    try
                    {
                        fileName = new String(fileName.getBytes(), "iso8859-1");// 解决中文
                        // 文件名问题
                    }
                    catch (UnsupportedEncodingException e1)
                    {
                        e1.printStackTrace();
                    }
                    response.setHeader("content-disposition",
                            "attachment; filename=" + fileName);// 设定输出文件头
                    // response.setContentType("application/msexcel");// 定义输出类型
                    OutputStream os = response.getOutputStream();
                    //
                    String templateFileName = ServletActionContext.getRequest()
                            .getRealPath("/")
                            + "/download/";
                    // 开始行数
                    int startRowNum = 3;
                    //
                    int startCell = 9;
                    //
                    if (templateFileType.indexOf("报纸") != -1)
                    {
                        //
                        templateFileName += "报纸排期模版.xlsx";
                        exportFlag = true;
                    }
                    else if (templateFileType.indexOf("杂志") != -1)
                    {
                        //
                        startCell = 10;
                        templateFileName += "杂志排期模版.xlsx";
                        exportFlag = true;
                    }
                    else if (templateFileType.indexOf("网络") != -1)
                    {
                        //
                        templateFileName += "网络排期模版.xlsx";
                        exportFlag = true;
                    }
                    else if (templateFileType.indexOf("户外") != -1)
                    {
                        //
                        templateFileName += "户外排期模板.xlsx";
                        exportFlag = true;
                    }
                    else if (templateFileType.indexOf("电台") != -1)
                    {
                        //
                        templateFileName += "电台排期模板.xlsx";
                        exportFlag = true;
                    }
                    else if (templateFileType.indexOf("电视") != -1)
                    {
                        //
                        startCell = 10;
                        templateFileName += "电视排期模板.xlsx";

                        exportFlag = true;
                    }
                    if (exportFlag)
                    {
                        // 创建工作薄引用
                        XSSFWorkbook book = new XSSFWorkbook(templateFileName);
                        // 创建工作表引用
                        XSSFSheet sheet = book.getSheetAt(0);
                        // 字体1
                        Font font1 = book.createFont();
                        font1.setFontHeightInPoints((short) 16);// 设置字号
                        font1.setFontName("幼圆");// 设置字体
                        // font1.setItalic(true);//设置是否斜体
                        // font1.setStrikeout(true);//设置是否强调
                        // 样式1
                        XSSFCellStyle cellStyle1 = book.createCellStyle();
                        cellStyle1.setBorderTop(BorderStyle.THIN);
                        cellStyle1.setBorderBottom(BorderStyle.THIN);
                        cellStyle1.setBorderLeft(BorderStyle.THIN);
                        cellStyle1.setBorderRight(BorderStyle.THIN);
                        cellStyle1.setFont(font1);
                        //
                        int firstDay = new Date((arrangementStartTime.substring(0,
                                8) + "01").replaceAll("-", "/")).getDay();
                        int maxDay = StringUtils.getMaxDayByMonth(arrangementStartTime);
                       //
                        if (templateFileType.indexOf("户外") != -1)
                        {
                            
                            // 月份
                            sheet.getRow(1)
                                    .getCell(0)
                                    .setCellValue(arrangementStartTime.substring(0,
                                            7));
                            // 地区
                            sheet.getRow(1)
                                    .getCell(16)
                                    .setCellValue(DatadicContext.getInstance()
                                            .getDatadicObject(city, "CITY")
                                            .getDatavalue());
                            // 广告周期
                            sheet.getRow(1)
                                    .getCell(14)
                                    .setCellValue(arrangementStartTime);
                            sheet.getRow(1)
                                    .getCell(15)
                                    .setCellValue(arrangementEndTime);
                            // 日期
                            sheet.getRow(1)
                                    .getCell(18)
                                    .setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                        }
                        else if (templateFileType.indexOf("网络") != -1)
                        {
                            // 月份
                            sheet.getRow(1)
                                    .getCell(0)
                                    .setCellValue(arrangementStartTime.substring(0,
                                            7));
                            // 地区
                            sheet.getRow(1)
                                    .getCell(15)
                                    .setCellValue(DatadicContext.getInstance()
                                            .getDatadicObject(city, "CITY")
                                            .getDatavalue());
                            // 广告周期
                            sheet.getRow(1)
                                    .getCell(13)
                                    .setCellValue(arrangementStartTime);
                            sheet.getRow(1)
                                    .getCell(14)
                                    .setCellValue(arrangementEndTime);
                            // 日期
                            sheet.getRow(1)
                                    .getCell(17)
                                    .setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                        }
                        else
                        {
                            // 日期
                            for (int i = 1; i <= 31; i++)
                            {
                                XSSFCell cell = sheet.getRow(2).getCell((i + startCell));
                                if (firstDay == 0 || firstDay == 6)
                                {
                                    // XSSFCellStyle cellStyle2 =
                                    // cell.getCellStyle();
                                    // cellStyle2.setFillBackgroundColor((short)
                                    // 60);
                                    // cell.setCellStyle(cellStyle2);
                                }
                                if (i > maxDay)
                                {
                                    cell.setCellValue("");
                                }
                                firstDay++;
                                if (firstDay == 7)
                                {
                                    // 重置日期
                                    firstDay = 0;
                                }
                            }
                            // 月份
                            sheet.getRow(1)
                                    .getCell(0)
                                    .setCellValue(arrangementStartTime.substring(0,
                                            7));
                            // 广告周期
                            sheet.getRow(1)
                                    .getCell(21)
                                    .setCellValue(DatadicContext.getInstance()
                                            .getDatadicObject(city, "CITY")
                                            .getDatavalue());
                            // 广告周期
                            sheet.getRow(1)
                                    .getCell(29)
                                    .setCellValue(arrangementStartTime);
                            sheet.getRow(1)
                                    .getCell(35)
                                    .setCellValue(arrangementEndTime);
                            // 月份
                            sheet.getRow(1)
                                    .getCell(44)
                                    .setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                        }
                        //
                        for (QueryArrangement arrangement : arrangements)
                        {
                            // 总计
                            int contentCell = 0;
                            // 本行下移
                            sheet.shiftRows(startRowNum,
                                    sheet.getLastRowNum(),
                                    1,
                                    true,
                                    false);
                            //
                            XSSFRow row = sheet.createRow(startRowNum);
                            // 名称
                            XSSFCell cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue(arrangement.getMediumName());
                            // 内容第二部分
                            List<String> tableFieldValues = arrangement.getTableFieldValue();
                            for (String tableFieldValue : tableFieldValues)
                            {
                                cell = row.createCell(contentCell++);
                                cell.setCellStyle(cellStyle1);
                                if(tableFieldValue == null){
                                    cell.setCellValue("");
                                }else{
                                    cell.setCellValue(tableFieldValue);
                                }
                                
                            }
                            // 内容第三部分
                            // 项目
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue(arrangement.getProjectName());
                            // 状态
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue(arrangement.getMediumStatus());
                            // 刊例价
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue(arrangement.getMediumPrice() + "");
                            // 折扣
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue(arrangement.getMediumOrientDiscount());
                            // 折扣刊例
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue(arrangement.getMediumDisPrice());
                            // 内容第四部分
                            String[] mediumArrangements = arrangement.getMediumArrangementArray();
                            String[] totalMediumArrangements = totalArrangement.getMediumArrangementArray();
                            firstDay = new Date((arrangementStartTime.substring(0,
                                    8) + "01").replaceAll("-", "/")).getDay();
                            if (templateFileType.indexOf("户外") != -1)
                            {
                                cell = row.createCell(contentCell++);
                                cell.setCellStyle(cellStyle1);
                                cell.setCellValue(arrangement.getFactStartTime());
                                cell = row.createCell(contentCell++);
                                cell.setCellStyle(cellStyle1);
                                cell.setCellValue(arrangement.getFactEndTime());
                            }
                            else if (templateFileType.indexOf("网络") != -1)
                            {
                                cell = row.createCell(contentCell++);
                                cell.setCellStyle(cellStyle1);
                                cell.setCellValue(arrangement.getFactStartTime());
                                cell = row.createCell(contentCell++);
                                cell.setCellStyle(cellStyle1);
                                cell.setCellValue(arrangement.getFactEndTime());
                            }
                            else
                            {
                                for (int i = 1; i <= 31; i++)
                                {
                                    cell = row.createCell(contentCell++);
                                    cell.setCellStyle(cellStyle1);
                                    if (i > maxDay)
                                    {
                                        cell.setCellValue("");
                                    }
                                    else
                                    {
                                        if (i >= startDay && i <= endDay)
                                        {
                                            if (firstDay == 0 || firstDay == 6)
                                            {
                                                // 周末
                                                cell.setCellValue(mediumArrangements[(i - startDay)]);
                                                if (bool)
                                                {
                                                    sheet.getRow(startRowNum + 1)
                                                            .getCell(contentCell - 1)
                                                            .setCellValue(totalMediumArrangements[(i - startDay)]);
                                                }
                                            }
                                            else
                                            {
                                                // 非周末
                                                cell.setCellValue(mediumArrangements[(i - startDay)]);
                                                if (bool)
                                                {
                                                    sheet.getRow(startRowNum + 1)
                                                            .getCell(contentCell - 1)
                                                            .setCellValue(totalMediumArrangements[(i - startDay)]);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            cell.setCellValue("--");
                                        }
                                        //
                                        firstDay++;
                                        //
                                        if (firstDay == 7)
                                        {
                                            // 重置日期
                                            firstDay = 0;
                                        }
                                    }
                                }
                            }
                            // 内容第五部分
                            // 次数
                            if (bool)
                            {
                                sheet.getRow(startRowNum + 1)
                                        .getCell(contentCell)
                                        .setCellValue(totalArrangement.getMediumAmount()+"");
                            }
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue(arrangement.getMediumAmount());
                            // 加收
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue("--");
                            // 加收
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue("--");
                            // 刊例总价 RMB
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue("--");
                            // 返还金额
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue("--");
                            // 呈批金额
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue("--");
                            // 税金
                            cell = row.createCell(contentCell++);
                            cell.setCellStyle(cellStyle1);
                            cell.setCellValue("--");
                            if (templateFileType.indexOf("电视") != -1)
                            {
                                cell = row.createCell(contentCell++);
                                cell.setCellStyle(cellStyle1);
                                cell.setCellValue("");
                                cell = row.createCell(contentCell++);
                                cell.setCellStyle(cellStyle1);
                                cell.setCellValue("");
                            }
                            else if (templateFileType.indexOf("户外") != -1)
                            {
                                cell = row.createCell((contentCell-1));
                                cell.setCellStyle(cellStyle1);
                                cell.setCellValue("");
                            }
                            else if (templateFileType.indexOf("杂志") != -1)
                            {

                            }
                            else if (templateFileType.indexOf("杂志") != -1)
                            {

                            }
                            else
                            {
                                // 备注
                                cell = row.createCell(contentCell++);
                                cell.setCellStyle(cellStyle1);
                                cell.setCellValue("");
                            }

                            // 行累加
                            startRowNum++;
                        }
                        // 总计
                        //
                        book.write(os);
                        os.close();
                    }
                }
            }
            // 打印退出方法体日志
            if (log.isInfoEnabled())
            {
                log.info("Exit CastDetailAction exportExcel() method, return String");
            }
            return resultName;
        }
        catch (Exception e)
        {
            // 打印异常信息
//            e.printStackTrace();
            // 打印异常方法体日志
            if (log.isInfoEnabled())
            {
                log.error("Exception CastDetailAction exportExcel() method, return String",
                        e);
            }
            // 重置返回值
            return ERROR;
        }

    }

    public String getArrangementStartTime()
    {
        return arrangementStartTime;
    }

    public void setArrangementStartTime(String arrangementStartTime)
    {
        this.arrangementStartTime = arrangementStartTime;
    }

    public String getArrangementEndTime()
    {
        return arrangementEndTime;
    }

    public void setArrangementEndTime(String arrangementEndTime)
    {
        this.arrangementEndTime = arrangementEndTime;
    }

    public String getMediaType()
    {
        return mediaType;
    }

    public void setMediaType(String mediaType)
    {
        this.mediaType = mediaType;
    }

    public String getYear()
    {
        return year;
    }

    public void setYear(String year)
    {
        this.year = year;
    }

    public String getCity()
    {
        return city;
    }

    public void setCity(String city)
    {
        this.city = city;
    }

    public int getCurrentPage()
    {
        return currentPage;
    }

    public void setCurrentPage(int currentPage)
    {
        this.currentPage = currentPage;
    }

    public PageBean getPage()
    {
        return page;
    }

    public void setPage(PageBean page)
    {
        this.page = page;
    }

    public List<Dictionary> getMediaTypeSelect()
    {
        return mediaTypeSelect;
    }

    public void setCastDetailService(CastDetailService castDetailService)
    {
        this.castDetailService = castDetailService;
    }

    public List<QueryArrangement> getArrangements()
    {
        return arrangements;
    }

    public List<String> getTableField()
    {
        return tableField;
    }

    public void setDictionaryService(DictionaryService dictionaryService)
    {
        this.dictionaryService = dictionaryService;
    }

    public List<String> getTableFieldValue()
    {
        return tableFieldValue;
    }

    public int getTotalDays()
    {
        return totalDays;
    }

    public int getTotalFields()
    {
        return totalFields;
    }

    public int getStartDay()
    {
        return startDay;
    }

    public int getEndDay()
    {
        return endDay;
    }

    public QueryArrangement getTotalArrangement()
    {
        return totalArrangement;
    }

    public List<Dictionary> getCitySelect()
    {
        return citySelect;
    }

}
